package com.ruoyi.business.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.ruoyi.business.domain.CarPackageAudit;
import com.ruoyi.business.domain.HistoryActivity;
import com.ruoyi.business.domain.ServiceItem;
import com.ruoyi.business.mapper.CarPackageAuditMapper;
import com.ruoyi.business.service.ICarPackageAuditService;
import com.ruoyi.business.service.IDefinitionNodeService;
import com.ruoyi.business.service.IServiceItemService;
import com.ruoyi.business.service.IprocessService;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysUserService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 审核列Service业务层处理
 *
 * @author x1ao
 * @date 2021-07-20
 */
@Service
public class CarPackageAuditServiceImpl implements ICarPackageAuditService {
    @Autowired
    private CarPackageAuditMapper carPackageAuditMapper;

    @Autowired
    private IprocessService processService;
    @Autowired
    private IServiceItemService serviceItemService;
    @Autowired
    private IDefinitionNodeService definitionNodeService;
    @Autowired
    private ISysUserService sysUserService;

    /**
     * 查询审核列
     *
     * @param id 审核列表ID
     * @return 审核列表
     */
    @Override
    public CarPackageAudit selectCarPackageAuditById(Long id) {
        return carPackageAuditMapper.selectCarPackageAuditById(id);
    }

    /**
     * 查询审核列表
     *
     * @param carPackageAudit 审核列表
     * @return 审核列表
     */
    @Override
    public List<CarPackageAudit> selectCarPackageAuditList(CarPackageAudit carPackageAudit) {
        carPackageAudit.setCreateBy(ShiroUtils.getUserId().toString());
        List<CarPackageAudit> carMaintenanceInfos = carPackageAuditMapper.selectCarPackageAuditList(carPackageAudit);
        for (CarPackageAudit audit : carMaintenanceInfos) {
            audit.setServiceItem(JSON.parseObject(audit.getServiceItemInfo(), ServiceItem.class));
            //根据数据中的流程实例id查询任务名称
            Task currentTask = processService.getTaskByProcessInstanceId(audit.getInstanceId());
            if (currentTask != null) {
                audit.setTaskId(currentTask.getId());
                audit.setTaskName(currentTask.getName());
            } else {
                //currentTask==null,说明任务已经结束了
                audit.setTaskName("任务已结束");
            }
        }
        return carMaintenanceInfos;
    }

    /**
     * 新增审核列表
     *
     * @param carPackageAudit 审核列表
     * @return 结果
     */
    @Override
    public int insertCarPackageAudit(CarPackageAudit carPackageAudit) {
        carPackageAudit.setCreateTime(DateUtils.getNowDate());
        return carPackageAuditMapper.insertCarPackageAudit(carPackageAudit);
    }

    /**
     * 修改审核列表
     *
     * @param carPackageAudit 审核列表
     * @return 结果
     */
    @Override
    public int updateCarPackageAudit(CarPackageAudit carPackageAudit) {
        return carPackageAuditMapper.updateCarPackageAudit(carPackageAudit);
    }

    /**
     * 删除审核列对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteCarPackageAuditByIds(String ids) {
        return carPackageAuditMapper.deleteCarPackageAuditByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除审核列表信息
     *
     * @param id 审核列表ID
     * @return 结果
     */
    @Override
    public int deleteCarPackageAuditById(Long id) {
        return carPackageAuditMapper.deleteCarPackageAuditById(id);
    }

    @Override
    public CarPackageAudit getCarPackageAudit(Long instanceId) {
        return carPackageAuditMapper.getCarPackageAudit(instanceId);
    }

    @Override
    public List<CarPackageAudit> selectTodoList(CarPackageAudit carPackageAudit) {
        //获取到当前登录用户id,根据用户id查询待办任务
        String userId = ShiroUtils.getUserId().toString();
        //查询符合条件的记录有多少条
        Long count = processService.getTodoTaskCount(CarPackageAudit.DEFINITION_KEY, userId);
        if (count > 0) {
            //获取前台传入的pageNum和PageSize
            PageDomain pageDomain = TableSupport.buildPageRequest();
            //如果符合条件的记录数大于0,才进行集合的查询
            List<Task> taskList = processService.selectTodoTaskList(
                    CarPackageAudit.DEFINITION_KEY,
                    userId, (pageDomain.getPageNum() - 1) * pageDomain.getPageSize(),
                    pageDomain.getPageSize());
            //需要返回给前台的数量
            List<CarPackageAudit> resultList = new ArrayList<>();
            for (Task task : taskList) {
                ProcessInstance instance = processService.getProcessInstanceById(task.getProcessInstanceId());
                String businessKey = instance.getBusinessKey();
                CarPackageAudit audit = carPackageAuditMapper.selectCarPackageAuditById(Long.valueOf(businessKey));
                audit.setTaskId(task.getId());
                audit.setTaskName(task.getName());
                audit.setServiceItem(JSON.parseObject(audit.getServiceItemInfo(), ServiceItem.class));
                resultList.add(audit);
            }
            //将页数封装成Page对象,里面包含总数,分页条数,页码
            Page page = new Page();
            page.setTotal(count);
            page.setPageNum(pageDomain.getPageNum());
            page.setPageSize(pageDomain.getPageSize());
            page.addAll(resultList);
            return page;
        }
        return Collections.EMPTY_LIST;
    }

    @Override
    @Transactional
    public void cancelApply(String instanceId, Long carPackageAuditId) {
        //1.修改快照表的信息(状态修改成撤销,审核人设置为空)
        CarPackageAudit audit = carPackageAuditMapper.selectCarPackageAuditById(carPackageAuditId);
        audit.setStatus(CarPackageAudit.STATUS_CANCEL);
        audit.setAuditors("");
        carPackageAuditMapper.updateCarPackageAudit(audit);
        //2.把服务项的状态修改成初始化
        //当前状态: 审核中
        //将ServiceItemInfo封装的Json格式数据解析成serviceItem对象,然后修改里面的状态
        ServiceItem item = JSON.parseObject(audit.getServiceItemInfo(), ServiceItem.class);
        //状态修改成初始化
        item.setAuditStatus(ServiceItem.AUDITSTATUS_INIT);
        serviceItemService.updateServiceItemNoCondition(item);
        //3.删除流程
        processService.deleteProcessInstance(instanceId);
    }

    @Override
    public void complete(String taskId, Boolean auditStatus, String comment) {
        //任务审批处理流程
        Task task = processService.getTaskByTaskId(taskId);
        ProcessInstance processInstance = processService.getProcessInstanceById(task.getProcessInstanceId());
        String businessKey = processInstance.getBusinessKey();
        //  任务属于候选人任务,先领取.
        //  给任务添加批注信息
        //  给任务添加流程变量 流程变量的名字是当前处理任务的id  流程的值 auditStatus
        processService.claimAndComplete(task, ShiroUtils.getUserId().toString(), auditStatus, comment);

        //判断流程是否已经结束了.
        //如果流程结束了,审核就通过
        //如何判断流程已经结束了?
        Task nextTask = processService.getTaskByProcessInstanceId(task.getProcessInstanceId());
        //根据流程实例ID获取下一个节点. 下一个节点为空: 流程已经结束,审核通过  下一个不为空: 流程没有结束
        CarPackageAudit audit = carPackageAuditMapper.selectCarPackageAuditById(Long.parseLong(businessKey));
        //下一个节点不为空: 流程节点没有结束
        if (nextTask != null) {
            List<String> userNameList = new ArrayList<>();
            //如果auditStatus为true
            if (auditStatus) {
                //根据下一个节点的Id在t_definition_node寻找该节点的审核人,给该节点设置候选人
                String taskDefinitionKey = nextTask.getTaskDefinitionKey();
                List<SysUser> auditorIdList = definitionNodeService.queryByTaskDefinitionKey(taskDefinitionKey);
                for (SysUser user : auditorIdList) {
                    processService.addCandidateUser(nextTask, Long.parseLong(user.getUserId().toString()));
                    userNameList.add(user.getUserName());
                }
                //保存到快照表
                audit.setAuditors(JSON.toJSONString(userNameList));
                //如果auditStatus为false
            } else {
                userNameList.add(audit.getCreateByName());
                //  获取到该流程发起人,给当前节点设置对应的候选人为当前流程发起人
                audit.setAuditors(audit.getCreateByName());
                processService.addCandidateUser(nextTask, Long.valueOf(audit.getCreateBy()));
                //  t_car_package_audit状态修改成审核拒绝 1
                audit.setStatus(CarPackageAudit.STATUS_REJECT);
            }
            audit.setAuditors(JSON.toJSONString(userNameList));
            carPackageAuditMapper.updateCarPackageAudit(audit);
        } else {
            //下一个节点为空: 流程已经结束
            //修改CarPackageAudit的状态,审核人字段设置为空
            audit.setAuditors("");
            audit.setStatus(CarPackageAudit.STATUS_PASS);
            carPackageAuditMapper.updateCarPackageAudit(audit);
            //  t_car_package_audit和t_service_item修改审核状态
            ServiceItem serviceItem = JSON.parseObject(audit.getServiceItemInfo(), ServiceItem.class);
            serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_APPROVED);
            serviceItemService.updateServiceItemNoCondition(serviceItem);
        }
    }

    @Override
    public void serviceItemsUpdate(Long carPackageAuditId, ServiceItem serviceItem) {
        serviceItemService.updateServiceItemNoCondition(serviceItem);
        CarPackageAudit audit = carPackageAuditMapper.selectCarPackageAuditById(carPackageAuditId);
        audit.setServiceItemInfo(JSON.toJSONString(serviceItem));
        carPackageAuditMapper.updateCarPackageAudit(audit);
    }

    @Override
    @Transactional
    public void reApply(String taskId, String carPackageAuditId) {
        //添加批注,领取任务,完成任务
        //1.根据任务ID查询任务对象
        Task task = processService.getTaskByTaskId(taskId);
        //重新设置流程变量
        CarPackageAudit audit = carPackageAuditMapper.selectCarPackageAuditById(Long.parseLong(carPackageAuditId));
        ServiceItem serviceItem = JSON.parseObject(audit.getServiceItemInfo(), ServiceItem.class);
        processService.setVariable(taskId, "money", serviceItem.getDiscountPrice().longValue());
        //领取并完成任务
        processService.claimAndComplete(task, ShiroUtils.getUserId().toString(), "重新申请");
        //完成任务后查询流程实例的下一个任务
        Task nextTask = processService.getTaskByProcessInstanceId(task.getProcessInstanceId());
        //指定出下一个任务的候选人
        List<String> auditors = new ArrayList<>();
        String taskDefinitionKey = nextTask.getTaskDefinitionKey();
        List<SysUser> auditorList = definitionNodeService.queryByTaskDefinitionKey(taskDefinitionKey);
        for (SysUser auditor : auditorList) {
            processService.addCandidateUser(nextTask, auditor.getUserId());
            auditors.add(auditor.getUserName());
        }
        //6.更新审核对象CarPackageAudit
        audit.setStatus(CarPackageAudit.STATUS_IN_ROGRESS);
        audit.setAuditors(JSON.toJSONString(auditors));
        carPackageAuditMapper.updateCarPackageAudit(audit);
    }

    @Override
    public List<CarPackageAudit> selectDoneList(CarPackageAudit carPackageAudit) {
        //获取当前登录用户id
        String userId = ShiroUtils.getUserId().toString();
        //获取已办任务的总数
        long count = processService.getHistoricTaskCount(CarPackageAudit.DEFINITION_KEY, userId);
        if (count > 0) {
            //获取前台传入的pageNum和PageSize
            PageDomain pageDomain = TableSupport.buildPageRequest();
            //如果符合条件的记录数大于0,才进行集合的查询
            List<HistoricTaskInstance> taskList = processService.selectDoneTaskList(
                    CarPackageAudit.DEFINITION_KEY,
                    userId, (pageDomain.getPageNum() - 1) * pageDomain.getPageSize(),
                    pageDomain.getPageSize());
            List<CarPackageAudit> resultList = new ArrayList<>();
            for (HistoricTaskInstance task : taskList) {
                //通过任务拿到流程实例对象
                HistoricProcessInstance instance = processService.getHistoricProcessInstanceById(task.getProcessInstanceId());
                String businessKey = instance.getBusinessKey();
                CarPackageAudit audit = carPackageAuditMapper.selectCarPackageAuditById(Long.parseLong(businessKey));
                audit.setServiceItem(JSON.parseObject(audit.getServiceItemInfo(), ServiceItem.class));
                audit.setTaskId(task.getId());
                audit.setTaskName(task.getName());
                audit.setDoneTime(task.getEndTime());
                resultList.add(audit);
            }
            //将页数封装成Page对象,里面包含总数,分页条数,页码
            Page page = new Page();
            page.setTotal(count);
            page.setPageNum(pageDomain.getPageNum());
            page.setPageSize(pageDomain.getPageSize());
            page.addAll(resultList);
            return page;
        } else {
            return Collections.EMPTY_LIST;
        }
    }

    @Override
    public List<HistoryActivity> selectHistoryList(String instanceId) {
        //查询集合
        List<HistoricActivityInstance> historyActivityInstances = processService.selectHistoryActivityList(instanceId);
        //返回的结果集
        List<HistoryActivity> resultList = new ArrayList<>();
        for (HistoricActivityInstance instance : historyActivityInstances) {
            HistoryActivity activity = new HistoryActivity();
            //把instance的所有属性,赋值给activity(把一个对象的属性拷贝到另一个对象中)
            BeanUtils.copyProperties(instance,activity);
            //查询批注信息
            String comment = processService.getComment(activity.getTaskId());
            activity.setComment(comment);
            resultList.add(activity);
            //设置任务的处理人
            String assignee = activity.getAssignee();
            if (StringUtils.isNotEmpty(assignee)){
                SysUser user = sysUserService.selectUserById(Long.parseLong(assignee));
                activity.setAssigneeName(user.getUserName());
            }
        }
        return resultList;
    }
}
